package cn.hzc.fortess.core.aop;

import cn.hzc.fortess.core.common.annotion.CheckType;
import cn.hzc.fortess.core.common.annotion.RequestPermission;
import cn.hzc.fortess.core.shiro.service.PermissionCheckService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.naming.NoPermissionException;
import java.lang.reflect.Method;


@Aspect
@Component
@Order(200)
public class PermissionAop {

    @Autowired
    private PermissionCheckService permissionCheckService;

    @Pointcut(value = "@annotation(cn.hzc.fortess.core.common.annotion.RequestPermission)")
    private void cutPermission() {

    }

    @Around("cutPermission()")
    public Object doPermission(ProceedingJoinPoint point) throws Throwable {
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        RequestPermission permission = method.getAnnotation(RequestPermission.class);
        boolean result = false;
        if (permission.checkType().equals(CheckType.AUTH_IDENT)) {
            result = permissionCheckService.checkResourceAuth(permission.value(), permission.logical());
        } else {
            result = permissionCheckService.checkRoleAuth(permission.value(), permission.logical());
        }
        if (result) {
            return point.proceed();
        } else {
            throw new NoPermissionException();
        }

    }

}
